import client, { DatasourceInstanceVo } from '@lib/client'
import { useClientRequest } from '@lib/utils/useClientRequest'
import { Button, Input, message, Modal, Space, Transfer } from 'antd'
import React, { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'

const { Search } = Input

export interface ISavePermissionButtonProps {
  refresh: () => void
  userId?: string
}

interface RecordType {
  key: string
  title: string
  description: string
}

const converterToRecordType = (instances: DatasourceInstanceVo[]) => {
  const res: RecordType[] = []
  instances.forEach((instance) => {
    res.push({
      key: instance.id + '',
      title: instance.name ?? '',
      description: instance.name ?? '',
    })
  })
  return res
}

export default function SavePermissionButton(
  props: ISavePermissionButtonProps
) {
  const { t } = useTranslation()
  const { refresh, userId } = props
  const [sourceData, setSourceData] = useState([] as RecordType[])
  const [targetData, setTargetData] = useState([] as string[])

  const [visible, setVisible] = useState(false)
  const [isPosting, setIsPosting] = useState(false)

  const {
    data: listInstanceResponse,
    sendRequest: listInstance,
  } = useClientRequest(
    (reqConfig) => client.getInstance().listInstances(reqConfig),
    { immediate: false }
  )

  const {
    data: getUserInstanceResponse,
    sendRequest: getUserInstance,
  } = useClientRequest(
    (reqConfig) =>
      client.getInstance().getUserInstancePermission(userId ?? '', reqConfig),
    { immediate: false }
  )

  const handleOpen = useCallback(async () => {
    await Promise.all([listInstance(), getUserInstance()])
    setVisible(true)
  }, [])

  const handleClose = useCallback(() => {
    setVisible(false)
    setIsPosting(false)
  }, [])

  const handleSubmit = async () => {
    try {
      setIsPosting(true)
      const r = await client.getInstance().saveUserInstancePermission({
        user_id: userId,
        instance_id: targetData.map((item) => parseInt(item)),
      })
      if (r.status == 200) {
        message.success('Success')
        setVisible(false)
        refresh()
      }
    } finally {
      setIsPosting(false)
    }
  }

  const onChange = (nextTargetKeys: string[]) => {
    setTargetData(nextTargetKeys)
  }

  useEffect(() => {
    setSourceData(converterToRecordType(listInstanceResponse?.instances ?? []))
    setTargetData(
      getUserInstanceResponse?.instances?.map((instance) => instance.id + '') ??
        []
    )
  }, [listInstanceResponse, getUserInstanceResponse])

  return (
    <>
      <a onClick={handleOpen}>{t('user_list.button.save_permission')}</a>
      <Modal
        title={t('user_list.modal.save_permission.title')}
        visible={visible}
        destroyOnClose
        onCancel={handleClose}
        width={600}
        footer={
          <Space>
            <Button onClick={handleClose}>
              {t('user_list.modal.save_permission.close')}
            </Button>
            <Button type="primary" loading={isPosting} onClick={handleSubmit}>
              {t('user_list.modal.save_permission.submit')}
            </Button>
          </Space>
        }
      >
        <Transfer
          dataSource={sourceData}
          titles={[
            t('user_list.modal.save_permission.source'),
            t('user_list.modal.save_permission.target'),
          ]}
          targetKeys={targetData}
          onChange={onChange}
          render={(item) => item.title ?? ''}
          oneWay
        />
      </Modal>
    </>
  )
}
